import React, { useState } from "react";
import "./index.scss";
import * as api from "api/index";
import classNames from "classnames";
import { useNavigate } from "react-router";
import { inject, observer } from "mobx-react";

function Login({ store }) {
  const navigate = useNavigate();

  let [phone, setPhoe] = useState(13800000000);
  let [code, setCode] = useState("");

  // 获取验证码
  const getCode = () => {
    api.$userGetSmsCode({ phone }).then((res) => {
      setCode(res.result.smsCode);
    });
  };

  // 登录
  const login = () => {
    let obj = {
      phone,
      smsCode: code,
    };
    api.$userLoginBySmsCode(obj).then((res) => {
      console.log(res);
      // 把token和phone存入store
      store.updatePhone(phone);
      store.updateToken(res.result.token);
      navigate('/my');
    });
  };

  return (
    <div className="content">
      <div className="login-box bg-fff">
        <div className="phone-box flex aic rel">
          <input
            value={phone}
            onChange={(ev) => {
              setPhoe(ev.target.value);
            }}
            name="phone"
            maxLength="11"
            className="phone pl-10 f16 reset-input"
            type="text"
            placeholder="请输入手机号，验证或登录"
          />
        </div>
        <div className="prove-box flex aic rel mt-5">
          <input
            value={code}
            onChange={(ev) => {
              setCode(ev.target.value);
            }}
            name="code"
            className="code f16 pl-10 reset-input"
            type="text"
            placeholder="请输入验证码"
          />
          <button onClick={getCode} className="get-code fff abs">
            获 取 验 证 码
          </button>
        </div>
        <div className="user-control flex jc-sa mt-10">
          <button className="cancel control-button">取 消</button>
          <button
            onClick={login}
            className={classNames("login control-button", { can: !!code })}
          >
            登 录
          </button>
        </div>
      </div>
    </div>
  );
}

export default inject("store")(observer(Login));
